package com.itita.ww2.handler.requesthandler.account;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Arrays;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smartfoxserver.v2.db.SFSDBManager;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.util.Country;
import com.smartfoxserver.v2.util.MD5;
import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.enums.ChannelEnum;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.utils.MathUtil;
import com.itita.ww2.utils.UUIDGenerator;
import com.itita.ww2.utils.UserUtil;
import com.itita.ww2.utils.handler.IRequestData;
import com.itita.ww2.utils.handler.IRequestOper;
import com.itita.ww2.utils.properties.ServerProperties;

/**
 * 自动注册
 * @author NorthLan
 *
 */
public class AutoSignUp implements IRequestOper, IRequestData {
	private static final Logger logger = LoggerFactory.getLogger(AutoSignUp.class);

	private SFSDBManager dbManager;

	@Override
	public void init(Object[] objs) {
		dbManager = (SFSDBManager) objs[0];
	}

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		// 只有游客才能注册
		if (!UserUtil.isGuest(user)) {
			MessageHandler.getInstance().sendMsg(requestCMD, null, user, WW2ExceptionCode.USER_NO_PERMISSION, false);
			return false;
		}
		String username = UUIDGenerator.nextUserName();
		/*
		 *  生成一坨Password,规则如下
		 *  MD5(username + salt(_nl))
		 */
		String pwdBack = MD5.getInstance().getHash(username + ServerProperties.getString("my.salt", "_nl")); // 回传密码
		String salt = MathUtil.GenerateSalt();
		String pwdReal = MD5.getInstance().getHash(username + ServerProperties.getString("my.salt", "_nl") + salt); // 真实密码
		int channel = ChannelEnum.DEFAULT.getValue(); // 此注册时使用默认渠道

		// 地理位置(根据IP)
		Country country = user.getCountry();
		String countryISO = "CN";
		if (country != null) {
			countryISO = country.getIsoCode();
			logger.info("user: [{}] auto-signup, country:{}/{}", username, user.getCountry().getName(), countryISO);
		} else {
			logger.info("user: [{}] auto-signup, country:{}/{}", username, "CN", countryISO);
		}

		// 写入用户表,当写入成功就算是成功了
		{
			String sql = "INSERT INTO `users` (`username`,`nickname`,`password`,`pwd_salt`,`channel`,`country`,`createTime`) VALUES (?,?,?,?,?,?,?)";
			dbManager.executeInsert(sql, Arrays.asList(username, username, pwdReal, salt, channel, countryISO,
					new Timestamp(DateTime.now(DateTimeZone.UTC).getMillis())).toArray());
		}

		// 回传
		ISFSObject backObj = SFSObject.newInstance();
		backObj.putUtfString("username", username);
		backObj.putUtfString("password", pwdBack);
		MessageHandler.getInstance().sendMsg(requestCMD, backObj, user, null, true);
		return true;
	}
}
